<template>
  <div v-loading="isLoading"
       class="container">
    <el-card>
      <template #header>
        <el-form ref="searchForm"
                 inline>
          <el-form-item label="商户类型"
                        prop="news_type">
            <el-select v-model="searchForm.shop_type_id"
                       placeholder="请选择商户类型">
              <el-option label="全部"
                         value="" />
              <el-option v-for="(oVal, oIdx) of type"
                         :key="oIdx"
                         v-bind="oVal" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary"
                       @click="getList()">查询</el-button>
          </el-form-item>
        </el-form>
        <div class="table_tool">
          <el-button type="primary"
                     icon="el-icon-plus"
                     @click="showAddOrSolve = true">新增</el-button>
        </div>
      </template>

      <el-table :data="tableData"
                border>
        <el-table-column prop="shop_name"
                         label="商户名称" />
        <el-table-column prop="contacts_name"
                         label="店主名称" />
        <el-table-column prop="contacts_phone"
                         label="联系电话" />
        <el-table-column prop="phones_num"
                         label="电话拨打次数" />
        <el-table-column prop="shop_time"
                         label="营业时间" />
        <el-table-column prop="shop_addr"
                         label="商户地址"
                         show-overflow-tooltip />
        <el-table-column prop="summary"
                         label="营业范围"
                         show-overflow-tooltip />
        <el-table-column label="操作"
                         width="240px"
                         align="center">
          <template slot-scope="{ row }">
            <el-button type="text"
                       @click="checkDetail(row)">查看详情</el-button>
            <el-button type="text"
                       @click="EditBusiness(row)">编辑</el-button>
            <el-button type="text"
                       class="red"
                       @click="delBusinessById(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <footer class="footer">
      <el-pagination background
                     layout="total, sizes, pager, jumper"
                     :current-page="searchForm.page"
                     :page-sizes="[10, 20, 30, 50, 100]"
                     :page-size="searchForm.per_page"
                     :total="tableTotal"
                     @size-change="changeSize"
                     @current-change="changeCurrent" />
    </footer>

    <el-dialog :title="this.builingForm.$id?'编辑商户':'新增商户'"
               :visible.sync="showAddOrSolve"
               width="1400px"
               @closed="resetForm()">
      <el-form ref="builingForm"
               :model="builingForm"
               label-width="7em">
        <el-form-item prop="$id"
                      hidden />

        <el-form-item class="span-3"
                      label="商户名称"
                      prop="shop_name">
          <el-input v-model="builingForm.shop_name"
                    placeholder="请输入商户名称" />
        </el-form-item>

        <el-form-item class="span-3"
                      label="店主姓名"
                      prop="contacts_name">
          <el-input v-model="builingForm.contacts_name"
                    placeholder="请输入店主姓名" />
        </el-form-item>

        <el-form-item class="span-3"
                      label="联系电话"
                      prop="contacts_phone">
          <el-input v-model="builingForm.contacts_phone"
                    minlength="11"
                    placeholder="请输入联系电话" />
        </el-form-item>

        <el-form-item class="span-3"
                      label="营业时间"
                      prop="shop_time">
          <el-input v-model="builingForm.shop_time"
                    placeholder="请输入营业时间" />
        </el-form-item>

        <el-form-item class="span-3"
                      label="所在小区"
                      prop="news_type">
          <el-select v-model="builingForm.subdistrict_id"
                     placeholder="请选择小区">
            <el-option v-for="(oVal, oIdx) of communityType"
                       :key="oIdx"
                       v-bind="oVal" />
          </el-select>
        </el-form-item>

        <el-form-item class="span-3"
                      label="详细地址"
                      prop="shop_addr">
          <el-input v-model="builingForm.shop_addr"
                    placeholder="请输入详细地址" />
        </el-form-item>

        <el-form-item class="span-2"
                      label="商户类型"
                      prop="news_type">
          <el-select v-model="builingForm.shop_type_id"
                     placeholder="请选择小区">
            <el-option v-for="(oVal, oIdx) of type"
                       :key="oIdx"
                       v-bind="oVal" />
          </el-select>
        </el-form-item>

        <el-form-item class="span-3"
                      label="用户联系次数"
                      prop="phones_num">
          <el-input v-model="builingForm.phones_num"
                    placeholder="请输入用户联系次数" />
        </el-form-item>

        <el-form-item label="营业范围"
                      prop="summary">
          <el-input v-model="builingForm.summary"
                    type="textarea"
                    row="3"
                    placeholder="请输入营业范围" />
        </el-form-item>

        <el-form-item label="封面图片"
                      prop="banner">
          <Upload v-model="builingForm.banner"
                  :file.sync="builingForm.banner" />
        </el-form-item>

        <el-form-item label="详情图片"
                      prop="imgs">
          <el-upload action="#"
                     list-type="picture-card"
                     :auto-upload="false"
                     :file-list="builingForm.imgs"
                     :on-change="handImgChange">
            <i slot="default"
               class="el-icon-plus" />
            <div slot="file"
                 slot-scope="{file}">
              <img class="el-upload-list__item-thumbnail"
                   :src="file.url"
                   alt="">
              <span class="el-upload-list__item-actions">
                <span class="el-upload-list__item-preview"
                      @click="handlePictureCardPreview(file)">
                  <i class="el-icon-zoom-in" />
                </span>
                <span class="el-upload-list__item-delete"
                      @click="handleRemove(file)">
                  <i class="el-icon-delete" />
                </span>
              </span>
            </div>
          </el-upload>
        </el-form-item>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%"
               :src="dialogImageUrl"
               alt="">
        </el-dialog>
      </el-form>

      <template #footer>
        <el-button type="primary"
                   :loading="loading.update"
                   @click="addBusiness()">提交</el-button>
      </template>
    </el-dialog>

    <el-dialog title="商家详情"
               :visible.sync="showAddOrEdit"
               width="1400px"
               @closed="resetForm()">
      <el-form ref="builingForm"
               :model="builingForm"
               label-width="7em">
        <el-form-item prop="$id"
                      hidden />

        <el-form-item class="span-3"
                      label="商户名称"
                      prop="shop_name">
          <el-input v-model="builingForm.shop_name"
                    readonly
                    placeholder="请输入商户名称" />
        </el-form-item>

        <el-form-item class="span-3"
                      label="店主姓名"
                      prop="contacts_name">
          <el-input v-model="builingForm.contacts_name"
                    readonly
                    placeholder="请输入店主姓名" />
        </el-form-item>

        <el-form-item class="span-3"
                      label="联系电话"
                      prop="contacts_phone">
          <el-input v-model="builingForm.contacts_phone"
                    readonly
                    placeholder="请输入联系电话" />
        </el-form-item>

        <el-form-item class="span-3"
                      label="营业时间"
                      prop="shop_time">
          <el-input v-model="builingForm.shop_time"
                    readonly
                    placeholder="请输入营业时间" />
        </el-form-item>

        <el-form-item class="span-3"
                      label="所在小区"
                      prop="news_type">
          <el-select v-model="builingForm.subdistrict_id"
                     disabled
                     placeholder="请选择小区">
            <el-option v-for="(oVal, oIdx) of communityType"
                       :key="oIdx"
                       v-bind="oVal" />
          </el-select>
        </el-form-item>

        <el-form-item class="span-3"
                      label="详细地址"
                      prop="shop_addr">
          <el-input v-model="builingForm.shop_addr"
                    readonly
                    placeholder="请输入详细地址" />
        </el-form-item>

        <el-form-item class="span-2"
                      label="商户类型"
                      prop="news_type">
          <el-select v-model="builingForm.shop_type_id"
                     disabled
                     placeholder="请选择小区">
            <el-option v-for="(oVal, oIdx) of type"
                       :key="oIdx"
                       v-bind="oVal" />
          </el-select>
        </el-form-item>

        <el-form-item class="span-3"
                      label="用户联系次数"
                      prop="phones_num">
          <el-input v-model="builingForm.phones_num"
                    readonly
                    placeholder="请输入用户联系次数" />
        </el-form-item>

        <el-form-item label="营业范围"
                      prop="summary">
          <el-input v-model="builingForm.summary"
                    readonly
                    type="textarea"
                    row="3"
                    placeholder="请输入营业范围" />
        </el-form-item>

        <el-form-item label="封面图片"
                      prop="banner">
          <Upload v-model="builingForm.banner"
                  :file.sync="builingForm.banner" />
        </el-form-item>

        <el-form-item label="详情图片"
                      prop="imgs">
          <el-upload action="#"
                     list-type="picture-card"
                     :auto-upload="false"
                     :file-list="builingForm.imgs"
                     :on-change="handImgChange">
            <i slot="default"
               class="el-icon-plus" />
            <div slot="file"
                 slot-scope="{file}">
              <img class="el-upload-list__item-thumbnail"
                   :src="file.url"
                   alt="">
              <span class="el-upload-list__item-actions">
                <span class="el-upload-list__item-preview"
                      @click="handlePictureCardPreview(file)">
                  <i class="el-icon-zoom-in" />
                </span>
                <span class="el-upload-list__item-delete"
                      @click="handleRemove(file)">
                  <i class="el-icon-delete" />
                </span>
              </span>
            </div>
          </el-upload>
        </el-form-item>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%"
               :src="dialogImageUrl"
               alt="">
        </el-dialog>
      </el-form>

      <template #footer>
        <el-button type="primary"
                   :loading="loading.update"
                   @click="closeDialog()">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import API from '@/api'
import { table, addOrEdit } from '@/utils/mixins'
import Upload from '@/components/Upload/SingleImage.vue'

export default {
  components: {
    Upload
  },
  mixins: [table, addOrEdit],
  data: () => ({
    showAddOrEdit: false, // 查看详情
    dialogVisible: false, // 图片预览
    showAddOrSolve: false, // 编辑
    dialogImageUrl: '', // 预览地址
    isLoading: true,
    tableData: [],
    tableTotal: 0,
    isKey: false,
    searchForm: {
      shop_type_id: '',
      page: 1, // 当前页码
      per_page: 10 // 每页条数
    },
    builingForm: {
      $id: '',
      shop_name: '',
      contacts_name: '',
      contacts_phone: '',
      phones_num: 0,
      shop_time: '',
      shop_addr: '',
      subdistrict_id: 1,
      shop_type_id: '',
      summary: '',
      banner: '',
      imgs: []
    },

    type: [],
    communityType: []
  }),

  created () {
    this.isLoading = true
    API.getBusinessType()
      .then(({ data }) => {
        const type = data.map(item => {
          return { label: item.name, value: item.id }
        })
        this.type = type
        // this.builingForm.shop_type_id=type[0].value
        this.getList()
      }).catch((err) => {
      }).finally(() => {
      })

    API.getCommunityList()
      .then(({ data }) => {
        const community = data.items.map(item => {
          return { label: item.name, value: item.id }
        })
        this.communityType = community
      })
  },

  methods: {
    // 获取列表
    getList () {
      this.isLoading = true
      const id = this.searchForm.shop_type_id
      API.getBusinessList(id, this.searchForm)
        .then(({ data }) => {
          data.items.forEach(item => {
            item.contacts_phone = item.contacts_phone.replace(/^(\d{3})\d{4}(\d+)/, '$1****$2')
          })
          this.tableData = data.items
          this.tableTotal = data.total
        }).catch((err) => {
          this.tableData = []
          this.tableTotal = 0
        }).finally(() => {
          this.isLoading = false
        })
    },

    // 分页
    changeSize (val) {
      this.searchForm.per_page = val
      this.searchForm.page = 1
      this.getList()
    },

    // 分页
    changeCurrent (val) {
      this.searchForm.page = val
      this.getList()
    },

    // 查看详情
    checkDetail (obj) {
      this.builingForm.$id = obj.id
      this.builingForm.shop_name = obj.shop_name
      this.builingForm.contacts_name = obj.contacts_name
      this.builingForm.contacts_phone = obj.contacts_phone
      this.builingForm.phones_num = obj.phones_num
      this.builingForm.shop_time = obj.shop_time
      this.builingForm.shop_addr = obj.shop_addr
      this.builingForm.subdistrict_id = obj.subdistrict_id
      this.builingForm.shop_type_id = obj.shop_type_id
      this.builingForm.summary = obj.summary
      this.builingForm.banner = obj.banner
      this.builingForm.imgs = JSON.parse(obj.imgs)
      this.builingForm.imgs = this.builingForm.imgs.map(item => {
        return { url: item }
      })
      this.showAddOrEdit = true
    },

    // 编辑活动
    EditBusiness (obj) {
      this.builingForm.$id = obj.id
      this.builingForm.shop_name = obj.shop_name
      this.builingForm.contacts_name = obj.contacts_name
      this.builingForm.contacts_phone = obj.contacts_phone
      this.builingForm.phones_num = obj.phones_num
      this.builingForm.shop_time = obj.shop_time
      this.builingForm.shop_addr = obj.shop_addr
      this.builingForm.subdistrict_id = obj.subdistrict_id
      this.builingForm.shop_type_id = obj.shop_type_id
      this.builingForm.summary = obj.summary
      this.builingForm.banner = obj.banner
      this.builingForm.imgs = JSON.parse(obj.imgs)
      this.builingForm.imgs = this.builingForm.imgs.map(item => {
        return { url: item }
      })
      this.showAddOrSolve = true
    },

    // 删除商户
    delBusinessById (id) {
      const _that = this
      this.$confirm(`是否删除这条商家数据？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
        .then(() => {
          API.delBusiness(id)
            .then(({ data }) => {
              this.$message.success('删除成功！')
            }).catch((err) => {
            }).finally(() => {
              _that.getList()
            })
        })
        .catch(() => {
        })
    },

    // 创建活动
    addBusiness () {
      if (!this.builingForm.shop_name.trim()) return this.$message.error('商户姓名不可为空~~')
      if (!this.builingForm.contacts_name.trim()) return this.$message.error('店主姓名不可为空~~')
      if (!this.builingForm.contacts_phone.trim()) return this.$message.error('联系电话不可为空~~')
      if (!this.builingForm.shop_time.trim()) return this.$message.error('营业时间不可为空~~')
      if (!this.builingForm.shop_addr.trim()) return this.$message.error('地址不可为空~~')
      if (!this.builingForm.summary.trim()) return this.$message.error('营业范围不可为空~~')
      if (!this.builingForm.banner) return this.$message.error('缩略图不可为空~~')
      if (this.builingForm.imgs.length == 0) return this.$message.error('详情图不可为空~~')

      const data = {
        shop_name: this.builingForm.shop_name,
        contacts_name: this.builingForm.contacts_name,
        contacts_phone: this.builingForm.contacts_phone,
        phones_num: this.builingForm.phones_num,
        shop_time: this.builingForm.shop_time,
        shop_addr: this.builingForm.shop_addr,
        subdistrict_id: this.builingForm.subdistrict_id,
        shop_type_id: this.builingForm.shop_type_id,
        summary: this.builingForm.summary,
        banner: this.builingForm.banner,
        imgs: JSON.stringify(this.builingForm.imgs.map(item => {
          return item.url
        }))
      }

      if (this.builingForm.$id) {
        const id = this.builingForm.$id
        API.editBusiness(id, data)
          .then(({ data }) => {
            this.$message.success('编辑成功！')
          }).catch((err) => {
          }).finally(() => {
            this.getList()
            this.closeDialog()
          })
      } else {
        API.addBusiness(data)
          .then(({ data }) => {
            this.$message.success('新增成功！')
          }).catch((err) => {
          }).finally(() => {
            this.getList()
            this.closeDialog()
          })
      }
    },

    // 关闭弹窗
    closeDialog () {
      console.log('关闭')
      this.resetForm()
      console.log('继续')
      this.showAddOrEdit = false
      this.showAddOrSolve = false
    },

    resetForm () {
      this.builingForm.$id = ''
      this.builingForm.shop_name = ''
      this.builingForm.contacts_name = ''
      this.builingForm.contacts_phone = ''
      this.builingForm.shop_time = ''
      this.builingForm.shop_addr = ''
      this.builingForm.summary = ''
      this.builingForm.banner = ''
      this.builingForm.imgs = []
      this.builingForm.subdistrict_id = 1
      this.builingForm.shop_type_id = 1
    },

    // 图片上传
    handImgChange ({ raw: file }) {
      this.uploadImg(file)
    },

    // 删除文件
    handleRemove (file) {
      console.log(file)
    },

    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },

    uploadImg: function (file) {
      const _that = this
      const forms = new FormData()
      forms.append('file', file)
      forms.append('app_key', 'weilai')
      forms.append('source_type', '2')
      this.$http.post(`https://files.meta-720.com/upload/v1/`, forms)
        .then(({ data }) => {
          const { source_path } = data.files[0]
          this.builingForm.imgs.push({ url: source_path })
        }).catch(() => {
        })
    }

  }
}
</script>

<style lang="scss" scoped>
::v-deep {
  .el-message-box {
    min-width: 400px;
  }
  .el-dialog {
    margin-top: 2vh !important;
  }
  .el-input .el-input__inner {
    border-radius: 4px !important;
  }
  .el-switch {
    transform: translateY(6px);
  }
  .el-message-box__message {
    position: absolute !important;
    top: 50% !important;
    left: 40px !important;
  }
  .el-form-item__label {
    font-size: 16px !important;
  }
}
</style>
